package com.atguigu.gulimall.juc.demo;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

class ReadWriteLockCache{
    Map<String,Object> container = new HashMap<String,Object>();
    ReadWriteLock lock = new ReentrantReadWriteLock();
    public void put(String key,Object value){
        lock.writeLock().lock();
        try {
            System.out.println("写"+key);
            container.put(key,value);
            System.out.println("写完成");
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            lock.writeLock().unlock();
        }
    }
    public Object get(String key){
        lock.readLock().lock();
        Object value = null;
        try {
            System.out.println("读取:"+key);
            value = container.get(key);
            System.out.println("读取完成 : "+value);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            lock.readLock().unlock();
        }
        return value;
    }
}

public class ReadWriteLockDemo {
    public static void main(String[] args) {
        ReadWriteLockCache cache = new ReadWriteLockCache();
        for (int i = 0; i < 100; i++) {
            int finalI = i;
            new Thread(()->{
                cache.put(String.valueOf(finalI),String.valueOf(finalI));
            },String.format("i%s",i)).start();
        }
        try {
            TimeUnit.SECONDS.sleep(5);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        for (int i = 0; i < 100; i++) {
            int finalI = i;
            new Thread(()->{
                Object o = cache.get(String.valueOf(finalI));
            },String.format("i%s",i)).start();
        }
    }
}
